﻿using Azure.Core;
using IdentityServer4.Extensions;
using IdentityServer4.Models;
using IdentityServer4.Services;
using Microsoft.AspNetCore.SignalR;
using System.Security.Claims;
using Windows.Admin.Contract;
using Windows.Infrastructure.Share.Extensions;
using Windows.Infrastructure.Share.Security;

namespace Windows.Identity.Api
{
    public class ProfileService: IProfileService
    {
        private readonly User.UserClient _client;
        // <summary>
        /// The claims factory.
        /// </summary>
        /// <summary>
        /// Initializes a new instance of the <see cref="TestUserProfileService"/> class.
        /// </summary>
        /// <param name="logger">The logger.</param>
        /// <param name="userRepository"></param>
        public ProfileService(User.UserClient client)
        {
            _client = client;
        }

        /// <summary>
        /// 只要有关用户的身份信息单元被请求（例如在令牌创建期间或通过用户信息终点），就会调用此方法
        /// </summary>
        /// <param name="context">The context.</param>
        /// <returns></returns>
        public virtual async Task GetProfileDataAsync(ProfileDataRequestContext context)
        {
            var sub = context.Subject?.GetSubjectId();
            if (sub == null) throw new Exception("No sub claim present");
            UserRequest request = new()
            {
                Id = sub.ToInt()
            };
            UserResponse response = await _client.GetByIdAsync(request);
            if (response == null)
            {
                //_logger?.LogWarning("No user found matching subject Id: {0}", sub);
            }
            else
            {
                List<Claim> claims = new()
                {
                    new Claim(WindowsClaimTypes.EmployeeId, response.EmployeeId.ToString()),
                    new Claim(ClaimTypes.NameIdentifier, response.Id.ToString()),
                    new Claim(ClaimTypes.Name, response.UserName ?? ""),
                    new Claim(ClaimTypes.MobilePhone, response.MobilePhone ?? ""),
                    new Claim(ClaimTypes.Email, response.Email ?? ""),
                    new Claim(ClaimTypes.GivenName, response.Name ?? ""),
                    new Claim(WindowsClaimTypes.IsAdmin, response.IsAdmin.ToString() ?? "False")
                };
                if (response.Licenses != null)
                {
                    foreach (var license in response.Licenses)
                    {
                        claims.Add(new Claim(WindowsClaimTypes.Licenses, license));
                    }
                }
                foreach (var id in response.RoleIds)
                {
                    claims.Add(new Claim(WindowsClaimTypes.RoleIds, id.ToString()));
                }
                foreach (var id in response.OrganizationIds)
                {
                    claims.Add(new Claim(WindowsClaimTypes.OrganizationIds, id.ToString()));
                }
                foreach (var id in response.PostIds)
                {
                    claims.Add(new Claim(WindowsClaimTypes.PostIds, id.ToString()));
                }
                foreach (var id in response.PostLevelIds)
                {
                    claims.Add(new Claim(WindowsClaimTypes.PostLevelIds, id.ToString()));
                }
                context.IssuedClaims = claims;
            }
        }

        /// <summary>
        /// 验证用户是否有效 例如：token创建或者验证
        /// </summary>
        /// <param name="context">The context.</param>
        /// <returns></returns>
        public virtual async Task IsActiveAsync(IsActiveContext context)
        {
            UserRequest request = new()
            {
                Id = context.Subject.GetSubjectId().ToInt()
            };
            UserResponse response = await _client.GetByIdAsync(request);
            context.IsActive = response.IsEnable;
        }
    }
}
